﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Devonline.Core
{
    /// <summary>
    /// 简易的事件流程模型
    /// </summary>
    /// <typeparam name="TEventArgs"></typeparam>
    public class EventPipeline<TEventArgs>
    {
        /// <summary>
        /// 构造方法
        /// </summary>
        public EventPipeline()
        {
            EventHandlers = new Dictionary<string, EventHandler<TEventArgs>>();
        }

        /// <summary>
        /// 数据订阅事件
        /// </summary>
        private IDictionary<string, EventHandler<TEventArgs>> EventHandlers { get; set; }
        /// <summary>
        /// 订阅事件
        /// </summary>
        /// <param name="eventName"></param>
        /// <param name="eventHandler"></param>
        public void Subscribe(string eventName, EventHandler<TEventArgs> eventHandler)
        {
            if (!EventHandlers.ContainsKey(eventName))
            {
                EventHandlers.Add(eventName, eventHandler);
            }
            else
            {
                EventHandlers[eventName] += eventHandler;
            }
        }
        /// <summary>
        /// 执行 eventName 开始的管道事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <param name="eventName">执行事件名称</param>
        public void Execute(object sender, TEventArgs e, string eventName)
        {
            if (eventName.IsNotNullOrEmpty())
            {
                var events = EventHandlers.Where(x => x.Key == eventName).Select(x => x.Value).ToList();
                if (events.IsNotNullOrEmpty())
                {
                    events.ForEach(hander => hander(sender, e));
                }
            }
        }
    }
}
